package com.example.leo.mycharmingstudent.a0908;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.leo.mycharmingstudent.R;
import com.example.leo.mycharmingstudent.a0905.ToastUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class StorageActivity extends AppCompatActivity {

    private static final String TAG = "StorageActivity";
    public static final int PERMISSION_REQUEST_CODE = 10000;

    //输入框  输入需要保存的内容
    private EditText etInputContent;
    //保存按钮   保存到外部存储  共有目录
    private Button btnSaveExternal;
    //读取按钮   从外部存储读取数据
    private Button btnReadExternal;
    //展示读取的数据
    private TextView tvContent;
    //保存按钮   保存到内部存储
    private Button btnSaveInternal;
    //读取按钮   从内部存储读取
    private Button btnReadInternal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_storage);

        findViews();
        initData();
        initEvent();

        requestPermission();
    }

    /**
     * 动态权限申请：
     * 1.检查权限
     * int permission = ContextCompat.checkSelfPermission
     * permission != PackageManager.PERMISSION_GRANTED
     * 2.申请权限
     * ActivityCompat.requestPermissions
     * 3.权限结果返回方法
     * onRequestPermissionsResult
     * 注意：如果不检查，直接动态申请权限，也可以
     */
    private void requestPermission() {
        //检查有没有所需的权限
        int permission = ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            //进入此处，说明没有权限
            //动态申请权限
            ActivityCompat.requestPermissions(
                    this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    PERMISSION_REQUEST_CODE
            );
        }
    }

    /**
     * 权限申请结果方法
     * 通知权限申请的结果
     */
    @Override
    public void onRequestPermissionsResult(
            int requestCode,
            @NonNull String[] permissions,
            @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            ToastUtil.showToast(this, "动态申请权限结果回来了~");
        }
    }

    private void findViews() {
        etInputContent = findViewById(R.id.et_input_content_activity_storage);
        btnSaveExternal = findViewById(R.id.btn_save_external_activity_storage);
        btnReadExternal = findViewById(R.id.btn_read_external_activity_storage);
        btnSaveInternal = findViewById(R.id.btn_save_internal_activity_storage);
        btnReadInternal = findViewById(R.id.btn_read_internal_activity_storage);
        tvContent = findViewById(R.id.tv_content_activity_storage);

    }

    private void initData() {

    }

    private void initEvent() {
        btnSaveExternal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveExternal();
            }
        });
        btnReadExternal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readExternal();
            }
        });
        btnSaveInternal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveInternal();
            }
        });
        btnReadInternal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readInternal();
            }
        });
    }

    /**
     * 保存数据到内部存储
     */
    private void saveInternal() {
        String path = getFilesDir().getAbsolutePath() + "/getFilesDir.txt";
        Log.e(TAG, path);
        File file = new File(path);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(etInputContent.getText().toString().getBytes());
            //流的关闭，最好放到finally方法体里面,参看saveExternal方法
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
    }

    /**
     * 从内部存储读取数据
     */
    private void readInternal() {
        String path = getFilesDir().getAbsolutePath() + "/getFilesDir.txt";
        File file = new File(path);
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int length = fileInputStream.read(bytes);
            String result = new String(bytes, 0, length);
            tvContent.setText(result);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存数据到外部存储   共有目录
     */
    private void saveExternal() {
        if (!Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED)) {
            ToastUtil.showToast(this, "外部存储不可用");
            //直接return表示不执行后续的代码
//            return;
        } else {
            ToastUtil.showToast(this, "外部存储可用");
            //获取路径
            String path = Environment.getExternalStorageDirectory() + "/0908.txt";
            Log.e(TAG, path);
            //根据路径，创建File对象
            File file = new File(path);

            FileOutputStream fileOutputStream = null;
            try {
                if (!file.exists()) {
                    //如果文件不存在，创建一个真实文件
                    file.createNewFile();
                }

                //创建文件输出流
                fileOutputStream = new FileOutputStream(file);
                //获取字符串的byte数组
                byte[] contentBytes = etInputContent.getText().toString().getBytes();
                //使用FileOutputStream对象，输出数据（字符串）到文件
                fileOutputStream.write(contentBytes);
//                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fileOutputStream != null) {
                    try {
                        //不要忘记关闭流，如果不关闭，会导致内存泄漏
                        //内存泄漏：用不到的数据，还没有办法被垃圾回收器回收。
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 读取数据从外部存储   共有目录
     */
    private void readExternal() {
        //获取一个路径
        String path = Environment.getExternalStorageDirectory() + "/0908.txt";
        File file = new File(path);
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            //一次读取到内存，如果文件过大，会导致内存溢出异常。
            //如何解决这个问题，待后续揭晓。
            int len = fileInputStream.read(bytes);
            String content = new String(bytes, 0, len);
            tvContent.setText(content);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
